package com.practice.java.practice4Mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

public class MybatisSqlSessionFactory {

    private static SqlSessionFactory sqlSessionFactory;
    private static final Logger logger = LoggerFactory.getLogger(MybatisSqlSessionFactory.class);

    public static SqlSessionFactory getSqlSessionFactory() {
        if(sqlSessionFactory == null) {
            synchronized (MybatisSqlSessionFactory.class) {
                if(sqlSessionFactory == null) {
                    try {
                        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
                        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                    } catch (IOException e) {
                        logger.error("open sql session error", e);
                    }
                }
            }
        }
        return sqlSessionFactory;
    }

    public static SqlSession openSession() {
        return getSqlSessionFactory().openSession();
    }

    public static void main(String[] args) {
        openSession();
    }

}
